package com.example.demo.controller;

import com.example.demo.entity.PostVO;
import com.example.demo.entity.User;
import com.example.demo.service.CommentService;
import com.example.demo.service.PostService;
import com.example.demo.service.TagService;
import io.swagger.v3.oas.annotations.Parameter;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.Objects;

@RestController
@RequestMapping("/posts")
public class PostController {

    @Autowired
    private PostService postService;

    @Autowired
    private UserController userController;

    @Autowired
    private TagService tagService;
    @Autowired
    private LikeController likeController;
    @Autowired
    private CommentService commentService;


    // 保存帖子
    @PostMapping("/save")
    public Map<String, Object> savePost(
            @Parameter(description = "帖子标题", required = true) @RequestParam String title,
            @Parameter(description = "帖子内容", required = true) @RequestParam String content,
            @Parameter(description = "标签名称列表") @RequestParam(required = false) List<String> tagNames,
            HttpServletRequest httpRequest) {
        try {
            // 获取当前用户 ID
            Map<String, Object> currentUserResponse = userController.getCurrentUser(httpRequest);
            if (!currentUserResponse.get("code").equals(200)) {
                return currentUserResponse; // 返回用户未登录或用户不存在的错误信息
            }
            Long userId = ((User) currentUserResponse.get("user")).getId();

            // 处理标签
            List<Long> tagIds = null;
            if (tagNames != null && !tagNames.isEmpty()) {
                tagIds = tagService.getOrCreateTags(tagNames); // 获取或创建标签
            }

            // 保存帖子
            Long postId = postService.savePost(userId, title, content, tagIds);

            return Map.of("code", 200, "message", "帖子保存成功");
        } catch (Exception e) {
            e.printStackTrace();
            return Map.of("code", 500, "message", "帖子保存失败: " + e.getMessage());
        }
    }

    // 查询帖子
    @GetMapping("/search")
    public ResponseEntity<Map<String, Object>> searchPosts(
            @RequestParam(value = "keyword", defaultValue = "") String keyword,
            @RequestParam(value = "tagName", defaultValue = "") String tagName,
            @RequestParam(value = "timeRange", defaultValue = "") String timeRange,
            @RequestParam(value = "page", defaultValue = "1") int page,
            @RequestParam(value = "pageSize", defaultValue = "10") int pageSize,
            HttpServletRequest request) { // 添加 HttpServletRequest 参数
        try {
            // 解析时间范围
            String startTime = null;
            String endTime = null;
            if (!timeRange.isEmpty()) {
                String[] times = timeRange.split(",");
                if (times.length == 1) {
                    // 查询某一天
                    startTime = times[0].trim();
                    endTime = times[0].trim();
                } else if (times.length == 2) {
                    // 查询某个时间段
                    startTime = times[0].trim();
                    endTime = times[1].trim();
                }
            }

            // 查询帖子列表
            List<PostVO> posts = postService.getPostsWithUserInfoByKeyword(keyword, tagName, startTime, endTime, page, pageSize, request);
            // 查询符合条件的帖子总数
            int total = postService.countPostsByKeyword(keyword, tagName, startTime, endTime);

            // 为每个帖子添加评论数量和二级评论数量
            for (PostVO post : posts) {
                Long postId = post.getId();
                int commentCount = commentService.getCommentCountByPostId(postId); // 获取评论数量
                int replyCount = commentService.getReplyCountByPostId(postId); // 获取二级评论数量
                post.setCommentCount(commentCount);
                post.setReplyCount(replyCount);
            }

            // 返回结果
            Map<String, Object> result = Map.of(
                    "posts", posts,
                    "total", total,
                    "page", page,
                    "pageSize", pageSize
            );
            // 返回 200 OK 和结果
            Map<String, Object> response = Map.of(
                    "code", 200,
                    "data", result
            );
            return new ResponseEntity<>(response, HttpStatus.OK);
        } catch (Exception e) {
            // 返回 500 Internal Server Error 和错误信息
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(Map.of("error", "服务器内部错误", "message", e.getMessage()));
        }
    }

    // 根据帖子 ID 查询帖子
    @GetMapping("/searchByPostId")
    public ResponseEntity<Map<String, Object>> getPostById(
            @RequestParam(value = "postId", required = true) Long postId,
            HttpServletRequest request) { // 添加 HttpServletRequest 参数
        try {
            // 查询帖子信息
            PostVO post = postService.getPostById(postId);
            if (post == null) {
                // 帖子不存在
                return ResponseEntity.status(HttpStatus.NOT_FOUND)
                        .body(Map.of("code", 404, "message", "帖子不存在"));
            }

            // 获取当前用户信息
            Map<String, Object> currentUserResponse = userController.getCurrentUser(request);
            Long userId = null;
            if (currentUserResponse.get("code").equals(200)) {
                userId = ((User) currentUserResponse.get("user")).getId();
            }

            // 获取点赞数
            Map<String, Object> likeCountResponse = likeController.getLikeCount(postId);
            if (likeCountResponse.get("code").equals(200)) {
                post.setLikeCount((Integer) likeCountResponse.get("likeCount"));
            }

            // 获取当前用户是否点赞
            if (userId != null) {
                Map<String, Object> isLikedResponse = likeController.isLiked(postId, request);
                if (isLikedResponse.get("code").equals(200)) {
                    post.setLiked((Boolean) isLikedResponse.get("isLiked"));
                }
            } else {
                post.setLiked(false); // 用户未登录，默认未点赞
            }

            // 获取评论数量和二级评论数量
            int commentCount = commentService.getCommentCountByPostId(postId); // 获取评论数量
            int replyCount = commentService.getReplyCountByPostId(postId); // 获取二级评论数量
            post.setCommentCount(commentCount);
            post.setReplyCount(replyCount);

            // 返回帖子信息
            Map<String, Object> response = Map.of(
                    "code", 200,
                    "data", post
            );
            return new ResponseEntity<>(response, HttpStatus.OK);
        } catch (Exception e) {
            // 返回 500 Internal Server Error 和错误信息
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(Map.of("error", "服务器内部错误", "message", e.getMessage()));
        }
    }

    // 判断当前用户是否为帖子作者
    @GetMapping("/{postId}/isOwner")
    public ResponseEntity<Map<String, Object>> isPostOwner(
            @PathVariable("postId") Long postId,
            HttpServletRequest request) {
        try {
            // 获取帖子详情
            PostVO post = postService.getPostById(postId);
            if (post == null) {
                // 帖子不存在的情况
                return ResponseEntity.status(HttpStatus.NOT_FOUND)
                        .body(Map.of("code", 404, "message", "帖子不存在"));
            }

            // 日志打印帖子信息
//            System.out.println("帖子信息：" + post);

            // 获取当前登录用户信息
            Map<String, Object> currentUserResponse = userController.getCurrentUser(request);
            if (!currentUserResponse.get("code").equals(200)) {
                // 用户未登录或会话失效
                System.out.println("用户未登录或会话失效：" + currentUserResponse);
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
                        .body(Map.of("code", 401, "message", "用户未登录"));
            }

            // 从用户信息中提取当前用户 ID
            Long currentUserId = ((User) currentUserResponse.get("user")).getId();
            System.out.println("当前登录用户 ID：" + currentUserId);

            // 判断是否为帖子作者
            boolean isOwner = Objects.equals(currentUserId, post.getUserId());
            System.out.println("当前用户是否为帖子作者：" + isOwner);

            // 返回判断结果
            return ResponseEntity.ok(Map.of("code", 200, "isOwner", isOwner));
        } catch (Exception e) {
            // 捕获异常并记录日志
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(Map.of("code", 500, "message", "服务器内部错误", "error", e.getMessage()));
        }
    }
    // 根据用户ID或用户名查询帖子
    @GetMapping("/searchByUser")
    public ResponseEntity<Map<String, Object>> searchPostsByUser(
            @RequestParam(value = "userId", required = false) Long userId,
            @RequestParam(value = "username", required = false) String username,
            @RequestParam(value = "page", defaultValue = "1") int page,
            @RequestParam(value = "pageSize", defaultValue = "10") int pageSize,
            HttpServletRequest request) {  // 添加 HttpServletRequest 参数
        try {
            // 检查是否至少传入一个参数
            if (userId == null && (username == null || username.trim().isEmpty())) {
                return ResponseEntity.badRequest().body(Map.of("code", 400, "message", "必须提供userId或username"));
            }

            // 分页查询用户的帖子
            List<PostVO> posts = postService.getPostsByUser(userId, username, page, pageSize);

            // 为每个帖子添加点赞信息、评论数量和回复数量
            for (PostVO post : posts) {
                Long postId = post.getId();

                // 获取点赞数
                Map<String, Object> likeCountResponse = likeController.getLikeCount(postId);
                if (likeCountResponse.get("code").equals(200)) {
                    post.setLikeCount((Integer) likeCountResponse.get("likeCount"));
                }

                // 判断当前用户是否已点赞
                Map<String, Object> currentUserResponse = userController.getCurrentUser(request);
                Long currentUserId = null;
                if (currentUserResponse.get("code").equals(200)) {
                    currentUserId = ((User) currentUserResponse.get("user")).getId();
                }
                if (currentUserId != null) {
                    Map<String, Object> isLikedResponse = likeController.isLiked(postId, request);
                    if (isLikedResponse.get("code").equals(200)) {
                        post.setLiked((Boolean) isLikedResponse.get("isLiked"));
                    }
                } else {
                    post.setLiked(false); // 默认未点赞
                }

                // 获取评论数量和回复数量
                int commentCount = commentService.getCommentCountByPostId(postId);
                int replyCount = commentService.getReplyCountByPostId(postId);
                post.setCommentCount(commentCount);
                post.setReplyCount(replyCount);
            }

            // 获取符合条件的帖子总数
            int total = postService.countPostsByUser(userId, username);

            // 返回结果
            Map<String, Object> result = Map.of(
                    "posts", posts,
                    "total", total,
                    "page", page,
                    "pageSize", pageSize
            );

            return ResponseEntity.ok(Map.of("code", 200, "data", result));
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(Map.of("code", 500, "message", "服务器内部错误", "error", e.getMessage()));
        }
    }
}
